package sk.vasicek.drinkmanager.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import sk.vasicek.drinkmanager.R;
import sk.vasicek.drinkmanager.domain.CustomDrink;
import sk.vasicek.drinkmanager.domain.Drink;
import sk.vasicek.drinkmanager.domain.DrinkEntry;
import sk.vasicek.drinkmanager.domain.DrinkUI;
import sk.vasicek.drinkmanager.domain.Drinker;
import sk.vasicek.drinkmanager.domain.Drinker.Sex;
import sk.vasicek.drinkmanager.domain.Language;
import sk.vasicek.drinkmanager.service.BackgroundAdapter;
import sk.vasicek.drinkmanager.service.CustomDrinkHelper;
import sk.vasicek.drinkmanager.service.DrinkHistoryHelper;
import sk.vasicek.drinkmanager.service.DrinkStatService;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.SlidingDrawer;
import android.widget.SlidingDrawer.OnDrawerOpenListener;
import android.widget.TextView;
import android.widget.Toast;

import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.GraphView.GraphViewData;
import com.jjoe64.graphview.GraphView.GraphViewSeries;
import com.jjoe64.graphview.LineGraphView;

public class DrinkManagerListActivity extends Activity {
	/** Called when the activity is first created. */
	// Stats
	private Button checkStatsButton;
	private TextView finalPriceText;
	private TextView alcoholConcentrationText;
	private RatingBar drunkRating;
	protected ImageButton settingsButton;
	protected ImageButton mapButton;
	protected ImageButton placesButton;
	protected ImageButton drinksButton;

	private static String TAG = "DrinkManagerListActivity";

	ArrayList<Drink> drinks = null;
	HashMap<Integer, DrinkUI> drinkTypes = null;
	SharedPreferences prefs;
	private DrinkHistoryHelper drinkHistoryHelper;
	private View customView;
	private CustomDrinkHelper customDrinkHelper;
	private ArrayList<String> drinkHistory;
	private ListView drinkHistoryList;
	private Button drinksHandle;
	private SlidingDrawer historySlider;
	private HashMap<String, DrinkEntry> drinkEntries;
	private ArrayList<String> drinkEntryList;
	private SlidingDrawer graphSlider;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		prefs = PreferenceManager.getDefaultSharedPreferences(this);

		this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		Configuration config = getBaseContext().getResources().getConfiguration();
		Locale locale = Language.getApplicationLanguage(this);
		Locale.setDefault(locale);
		config.locale = locale;
		getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
		this.setContentView(R.layout.drinkmanagerlist);
		Log.d(TAG, "Started drink manager");

		// stats controllers
		this.checkStatsButton = (Button) this.findViewById(R.id.checkStatsButton);
		this.drunkRating = (RatingBar) this.findViewById(R.id.drunkRating);
		this.finalPriceText = (TextView) this.findViewById(R.id.finalPriceText);
		this.alcoholConcentrationText = (TextView) this.findViewById(R.id.alcoholConcentration);
		initCustomDrinks();

		BackgroundAdapter.updateBackgroundFromPrefs(prefs, this);

		this.drinkHistoryList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int no, long arg3) {
				// Toast toast = Toast.makeText(getApplicationContext(),
				// "You picked " + contactPhoneList.get(no),
				// Toast.LENGTH_SHORT);
				// toast.show();
				// Intent intent = new Intent(getApplicationContext(),
				// DrinkMapDetailActivity.class);
				final DrinkEntry drinkEntry = drinkEntries.get(drinkEntryList.get(no));

				AlertDialog.Builder builder = new AlertDialog.Builder(DrinkManagerListActivity.this);
				builder.setMessage(getResources().getText(R.string.entryRemovePrompt)).setCancelable(true)
						.setPositiveButton(getResources().getText(R.string.yesAnswer), new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								if (drinkEntry != null) {
									drinkHistoryHelper.removeDrinkEntry(drinkEntry);

									updateCounts();
									updateStatistics();
									updateDrinkGraph();
								}
							}
						}).setNegativeButton(getResources().getText(R.string.noAnswer), new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
				AlertDialog alert = builder.create();
				alert.show();
			}

		});

		this.historySlider = (SlidingDrawer) this.findViewById(R.id.historySlider);
		historySlider.setOnDrawerOpenListener(new OnDrawerOpenListener() {

			@Override
			public void onDrawerOpened() {
				updateDrinkHistory();
			}
		});

		this.graphSlider = (SlidingDrawer) this.findViewById(R.id.graphSlider);
		graphSlider.setOnDrawerOpenListener(new OnDrawerOpenListener() {
			@Override
			public void onDrawerOpened() {
				updateDrinkGraph();
			}

		});

		this.checkStatsButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				updateCounts();
				updateStatistics();
				updateDrinkHistory();
			}
		});
		this.mapButton = (ImageButton) this.findViewById(R.id.map);
		mapButton.setVisibility(View.VISIBLE);
		this.mapButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Toast.makeText(getApplicationContext(),
				// getResources().getText(R.string.alreadyToast),
				// Toast.LENGTH_SHORT).show();

				Intent intent = new Intent(getApplicationContext(), MapsOverlayActivity.class);
				startActivity(intent);
			}
		});
		this.placesButton = (ImageButton) this.findViewById(R.id.places);
		placesButton.setVisibility(View.VISIBLE);
		this.placesButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(), DrinkPlacesActivity.class);
				startActivity(intent);
			}
		});

		this.settingsButton = (ImageButton) this.findViewById(R.id.settings);
		settingsButton.setVisibility(View.VISIBLE);
		this.settingsButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
				startActivity(intent);
			}
		});

		this.drinksButton = (ImageButton) this.findViewById(R.id.drinks);

		this.drinksButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Intent intent = new Intent(getApplicationContext(),
				// DrinkManagerActivity.class);
				// startActivity(intent);
				Toast.makeText(getApplicationContext(), getResources().getText(R.string.alreadyToast), Toast.LENGTH_SHORT).show();

			}
		});
	}

	private float alcoholMassCoeficientBySex = new Float("0.68");
	private float bodyWeight = new Float("75");
	double alcoholConcentration = 0.0d;
	double drunkRate = this.alcoholConcentration * 100d;

	public void updateStatistics() {
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		drinkHistoryHelper = new DrinkHistoryHelper(this);
		int gender = Integer.parseInt(prefs.getString("Gender", "1"));
		switch (gender) {
		case 1:
			this.alcoholMassCoeficientBySex = 0.70f;
			break;
		case 2:
			this.alcoholMassCoeficientBySex = 0.60f;
			break;
		default:
			Log.d(TAG, "In alcoholMassCoeficientBySex loading had to take default value");
			this.alcoholMassCoeficientBySex = 0.70f;
			break;
		}
		Log.d(TAG, "alcoholMassCoeficientBySex = " + this.alcoholMassCoeficientBySex);
		this.bodyWeight = Float.parseFloat(prefs.getString("Weight", "75").replaceAll(",", "."));
		Log.d(TAG, "bodyWeight = " + this.bodyWeight);

		DrinkStatService statService = new DrinkStatService();
		ArrayList<DrinkEntry> drinkEntries = drinkHistoryHelper.getDrinkEntryAfter(new Date((long) (new Date().getTime() - DrinkStatService.MILLIS_TO_HOURS_DIVIDER * 24l)));
		alcoholConcentration = statService.calculateAlcoholConcentration(drinkEntries, new Drinker("", Sex.values()[gender - 1], bodyWeight));
		this.drunkRate = this.alcoholConcentration * 1000f * 3f;
		Log.d(TAG, "blood alcohol concentration = " + this.alcoholConcentration);

		float finalPrice = statService.calculateFinalPrice(drinkEntries);
		DrinkManagerListActivity.this.finalPriceText.setText(String.valueOf(finalPrice) + "");
		Log.d(TAG, "price = " + String.valueOf(finalPrice) + "");
		String aC = String.valueOf(this.alcoholConcentration * 1000f);
		String concentration = aC.length() > 7 ? aC.substring(0, 7) : aC;
		DrinkManagerListActivity.this.alcoholConcentrationText.setText(concentration + " \u2030");
		Log.d(TAG, "alcoholConcentration = " + concentration + " \u2030");

		DrinkManagerListActivity.this.drunkRating.setRating((float) this.drunkRate);
	}

	private void initCustomDrinks() {
		this.drinks = new ArrayList<Drink>();
		drinkTypes = new HashMap<Integer, DrinkUI>();
		DrinkUI beer = new DrinkUI(R.string.beerLabel, "beerButton", "beerPrice", "beerLabel", "beerCount");
		DrinkUI wine = new DrinkUI(R.string.wineLabel, "wineButton", "winePrice", "wineLabel", "wineCount");
		DrinkUI shot = new DrinkUI(R.string.shotLabel, "shotButton", "shotPrice", "shotLabel", "shotCount");

		// drinkTypes.add(beer);
		// drinkTypes.add(wine);
		// drinkTypes.add(shot);
		customDrinkHelper = new CustomDrinkHelper(this);
		CustomDrink firstDrink = null;
		CustomDrink secondDrink = null;
		CustomDrink thirdDrink = null;

		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		int backgroundId = Integer.parseInt(prefs.getString("BackgroundPref", "0"));

		ArrayList<CustomDrink> customDrinksLoaded = customDrinkHelper.getAllCustomDrinks();

		if (customDrinksLoaded.size() < 3) {
			// Drink Agent
			// // ID: 1
			// CustomDrink drink = new CustomDrink(0.16, 0.1, "Martiny", "");
			// drink.setId(1);
			// customDrinkHelper.updateCustomDrinkOrInsert(drink.getId(),
			// drink);
			// // ID: 2
			// drink = new CustomDrink(0.42, 0.04, "Vodka", "");
			// drink.setId(2);
			// customDrinkHelper.updateCustomDrinkOrInsert(drink.getId(),
			// drink);
			// // ID: 3
			// drink = new CustomDrink(0.14, 0.2, "Champagne", new String[] {
			// "Champagne", "Šampanské", "Šampanský" }, "");
			// drink.setId(3);
			// customDrinkHelper.updateCustomDrinkOrInsert(drink.getId(),
			// drink);
			// // ID: 4
			// drink = new CustomDrink(0.16, 0.5,
			// getResources().getText(R.string.wineLabel).toString(), "");
			// drink.setId(4);
			// customDrinkHelper.updateCustomDrinkOrInsert(drink.getId(),
			// drink);
			// // ID: 5
			// drink = new CustomDrink(0.0, 0.2, "Sparkling water", new String[]
			// { "Sparkling water", "Minerálna voda", "Minerální voda" }, "");
			// drink.setId(5);
			// customDrinkHelper.updateCustomDrinkOrInsert(drink.getId(),
			// drink);
			// // ID: 6
			// drink = new CustomDrink(0.42, 0.1, "Whiskey", "");
			// drink.setId(6);
			// customDrinkHelper.updateCustomDrinkOrInsert(drink.getId(),
			// drink);
			// // ID: 7
			// drink = new CustomDrink(0.42, 0.2, "Cognac", new String[] {
			// "Cognac", "Koňak", "Koňak" }, "");
			// drink.setId(7);
			// customDrinkHelper.updateCustomDrinkOrInsert(drink.getId(),
			// drink);
			// Drink Manager
			// ID: 1
			CustomDrink drink = new CustomDrink(0.05, 0.5, getResources().getText(R.string.beerLabel).toString(), "");
			drink.setId(1);
			customDrinkHelper.updateCustomDrinkOrInsert(drink.getId(), drink);
			// ID: 2
			drink = new CustomDrink(0.16, 0.2, getResources().getText(R.string.wineLabel).toString(), "");
			drink.setId(1);
			customDrinkHelper.updateCustomDrinkOrInsert(drink.getId(), drink);
			// ID: 3
			drink = new CustomDrink(0.42, 0.05, getResources().getText(R.string.shotLabel).toString(), "");

			drink.setId(1);

			customDrinkHelper.updateCustomDrinkOrInsert(drink.getId(), drink);

		}

		// switch (Style.values()[backgroundId]) {
		// case Dark:
		// firstDrink = customDrinkHelper.getCustomDrinkByID(1);
		// secondDrink = customDrinkHelper.getCustomDrinkByID(2);
		// thirdDrink = customDrinkHelper.getCustomDrinkByID(3);
		// break;

		// case Steel:
		// firstDrink = customDrinkHelper.getCustomDrinkByID(4);
		// secondDrink = customDrinkHelper.getCustomDrinkByID(3);
		// thirdDrink = customDrinkHelper.getCustomDrinkByID(5);
		// break;

		// case Titan:
		// firstDrink = customDrinkHelper.getCustomDrinkByID(6);
		// secondDrink = customDrinkHelper.getCustomDrinkByID(7);
		// thirdDrink = customDrinkHelper.getCustomDrinkByID(4);
		// break;
		// default:

		firstDrink = customDrinkHelper.getCustomDrinkByID(1);
		secondDrink = customDrinkHelper.getCustomDrinkByID(2);
		thirdDrink = customDrinkHelper.getCustomDrinkByID(3);
		// break;

		// }
		boolean defaultPricesEnabled = prefs.getBoolean("EnablePrice", true);

		if (!defaultPricesEnabled) {
			firstDrink.setPrice(0d);
			secondDrink.setPrice(0d);
			thirdDrink.setPrice(0d);
		}

		ArrayList<CustomDrink> customDrinks = new ArrayList<CustomDrink>();
		customDrinks.add(thirdDrink);
		customDrinks.add(secondDrink);
		customDrinks.add(firstDrink);

		boolean customDrinksEnabled = prefs.getBoolean("EnableDrinks", true);
		if (customDrinksEnabled) {
			customDrinksLoaded = customDrinkHelper.getAllCustomDrinksAfterID(3l);
			if (!defaultPricesEnabled) {
				for (CustomDrink customDrink : customDrinks) {
					customDrink.setPrice(0d);
				}
			}
			customDrinks.addAll(customDrinksLoaded);
		}
		drinkTypes.clear();
		for (CustomDrink customDrink : customDrinks) {
			if (customDrink != null) {
				String drinkName = customDrink.getName();
				DrinkUI drinkUI = new DrinkUI(drinkName, drinkName + "Button", drinkName + "Price", drinkName + "Label", drinkName + "Count");
				drinkUI.setCustomDrink(customDrink);
				drinkTypes.put(drinkUI.getCustomDrink().getId(), drinkUI);
			}
		}

		drinkHistoryHelper = new DrinkHistoryHelper(this);
		LinearLayout list = (LinearLayout) this.findViewById(R.id.drinkControllList);
		LayoutInflater linflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		list.removeAllViews();
		list.setGravity(backgroundId);
		for (final DrinkUI drinkUI : drinkTypes.values()) {
			Log.d(TAG, "Generating " + drinkUI.getLabelText(this) + " controll");
			// final CustomDrink customDrink = drinkUI.getCustomDrink();
			customView = linflater.inflate(R.layout.drink_controll, null);
			// customView.setScrollContainer(false);
			Button drinkButton = (Button) customView.findViewById(R.id.drinkButton);
			final EditText drinkPrice = (EditText) customView.findViewById(R.id.drinkPrice);
			drinkPrice.setText("" + drinkUI.getCustomDrink().getPrice());
			TextView drinkLabel = (TextView) customView.findViewById(R.id.drinkLabel);
			TextView drinkCount = (TextView) customView.findViewById(R.id.drinkCount);

			drinkButton.setId(drinkUI.getButtonId());
			drinkUI.setButton(drinkButton);
			drinkPrice.setId(drinkUI.getPriceId());
			drinkUI.setPrice(drinkPrice);
			drinkLabel.setId(drinkUI.getLabelId());
			drinkUI.setLabel(drinkLabel);
			drinkCount.setId(drinkUI.getCountId());
			drinkUI.setCount(drinkCount);
			drinkLabel.setText(drinkUI.getLabelText(this));
			drinkButton.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					String name = drinkUI.getCustomDrink().getName();
					if (name == null || "".equals(name.trim())) {
						name = getResources().getText(R.string.drinkLabelGeneric).toString();
						drinkUI.getCustomDrink().setName(name);
					}
					String priceString = drinkPrice.getText().toString().trim().replaceAll(",", ".");
					double price = Double.parseDouble("".equals(priceString) ? "0.0" : priceString);
					drinkUI.getCustomDrink().setPrice(price);
					drinkHistoryHelper.insertDrinkEntry(new DrinkEntry(drinkUI.getCustomDrink(), new Date()));
					// Toast.makeText(DrinkManagerListActivity.this, "Added:" +
					// v.getId() + " name:" + name, Toast.LENGTH_SHORT).show();
					updateCounts();
					updateStatistics();
					updateDrinkGraph();
				}
			});

			list.addView(customView);
		}
		updateCounts();
		updateStatistics();
		updateDrinkGraph();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = this.getMenuInflater();
		inflater.inflate(R.menu.optionmenu, menu);
		MenuItem settings = menu.findItem(R.id.settings);
		settings.setIntent(new Intent(this, SettingsActivity.class));
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.exit:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(getResources().getText(R.string.exitPrompt)).setCancelable(true).setPositiveButton(getResources().getText(R.string.yesAnswer), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					Toast.makeText(DrinkManagerListActivity.this, getResources().getText(R.string.exitMessage), Toast.LENGTH_SHORT).show();
					DrinkManagerListActivity.this.finish();
				}
			}).setNegativeButton(getResources().getText(R.string.noAnswer), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
			AlertDialog alert = builder.create();
			alert.show();
			// this.onDestroy();
			return true;
		case R.id.settings:
			Intent settingsIntent = item.getIntent();
			DrinkManagerListActivity.this.startActivityForResult(settingsIntent, 0);
			return true;
		case android.R.id.home:
			Toast.makeText(DrinkManagerListActivity.this, getResources().getText(R.string.alreadyToast), Toast.LENGTH_SHORT).show();
			// Intent intent = new Intent(this, DrinkManagerListActivity.class);
			// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			// startActivity(intent);
			return true;
		case R.id.drinks:
			Toast.makeText(DrinkManagerListActivity.this, getResources().getText(R.string.alreadyToast), Toast.LENGTH_SHORT).show();
			return true;
		case R.id.places:
			Intent placesIntent = new Intent(this, DrinkPlacesActivity.class);
			this.startActivityForResult(placesIntent, 0);
			return true;
		case R.id.custom:
			Intent customIntent = new Intent(this, CustomDrinksActivity.class);
			this.startActivityForResult(customIntent, 0);
			return true;
		case R.id.history:
			Intent historyIntent = new Intent(this, DrinkHistoryActivity.class);
			this.startActivityForResult(historyIntent, 0);
			return true;
		case R.id.graphs:
			Intent graphsIntent = new Intent(this, DrinkGraphActivity.class);
			this.startActivityForResult(graphsIntent, 0);
			return true;
		case R.id.back:
			Intent backIntent = new Intent(this, BackgroundChooserActivity.class);
			this.startActivityForResult(backIntent, 0);
			return true;
		case R.id.map:
			Intent mapsIntent = new Intent(this, MapsOverlayActivity.class);
			DrinkManagerListActivity.this.startActivityForResult(mapsIntent, 0);

			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void updateCounts() {
		// Calendar cal = Calendar.getInstance();
		// cal.clear(Calendar.HOUR_OF_DAY);
		// cal.clear(Calendar.MINUTE);
		// cal.clear(Calendar.SECOND);
		// cal.clear(Calendar.MILLISECOND);
		// Date date = cal.getTime();
		Date date = new Date((long) (new Date().getTime() - DrinkStatService.MILLIS_TO_HOURS_DIVIDER * 24l));
		drinkHistoryHelper = new DrinkHistoryHelper(this);
		customDrinkHelper = new CustomDrinkHelper(this);
		if (drinkTypes != null) {
			for (DrinkUI drinkUI : drinkTypes.values()) {
				Log.d(TAG, "Generating " + drinkUI.getLabelText(this) + " controll");

				final CustomDrink customDrink = drinkUI.getCustomDrink();

				Button drinkButton = drinkUI.getButton();
				EditText drinkPrice = drinkUI.getPrice();
				TextView drinkLabel = drinkUI.getLabel();
				TextView drinkCount = drinkUI.getCount();
				Integer drinkEntriesCount = drinkHistoryHelper.countDrinkEntryAfterForName(date, customDrink.getName());

				boolean defaultPricesEnabled = prefs.getBoolean("EnablePrice", true);
				if (!defaultPricesEnabled) {
					String name = customDrink.getName();
					if (name == null || "".equals(name.trim())) {
						name = getResources().getText(R.string.drinkLabelGeneric).toString();
						customDrink.setName(name);
					}
					customDrinkHelper.updateCustomDrinkOrInsert(customDrink.getId(), customDrink);
				}

				Log.d(TAG, "Updated drinks for " + customDrink.getName() + ":" + drinkEntriesCount);
				if (customDrink != null && drinkPrice != null)
					drinkPrice.setText("" + customDrink.getPrice());
				if (drinkLabel != null)
					drinkLabel.setText("" + drinkUI.getLabelText(this));
				if (drinkCount != null)
					drinkCount.setText("" + drinkEntriesCount);
			}
		}
	}

	private void updateDrinkGraph() {
		BackgroundAdapter.updateBackgroundFromPrefs(prefs, this);
		LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
		layout.removeAllViews();

		int gender = Integer.parseInt(prefs.getString("Gender", "1"));
		switch (gender) {
		case 1:
			this.alcoholMassCoeficientBySex = 0.70f;
			break;
		case 2:
			this.alcoholMassCoeficientBySex = 0.60f;
			break;
		default:
			Log.d(TAG, "In alcoholMassCoeficientBySex loading had to take default value");
			this.alcoholMassCoeficientBySex = 0.70f;
			break;
		}
		Log.d(TAG, "alcoholMassCoeficientBySex = " + this.alcoholMassCoeficientBySex);
		this.bodyWeight = Float.parseFloat(prefs.getString("Weight", "75").replaceAll(",", "."));
		Log.d(TAG, "bodyWeight = " + this.bodyWeight);

		DrinkStatService statService = new DrinkStatService();
		DrinkHistoryHelper drinkHistoryHelper = new DrinkHistoryHelper(this);
		ArrayList<DrinkEntry> drinkEntries = drinkHistoryHelper.getAllDrinksFromHistory();

		ArrayList<String> timeLabels = new ArrayList<String>();
		Float[] data = statService.generateAlcoholConcentrationGraphInput(drinkEntries, new Drinker("", Sex.values()[gender - 1], bodyWeight), 12l, 24l, timeLabels);
		GraphViewData[] graphViewDatas = new GraphViewData[statService.dataSize];
		for (int i = 0; i < data.length; i++) {
			graphViewDatas[i] = new GraphViewData(i, data[/* (data.length - 1) - */i] * 1000d);
		}
		GraphView graphView = new LineGraphView(getApplicationContext(), "Drink Graphs");
		// add data
		graphView.addSeries(new GraphViewSeries(graphViewDatas));
		// set view port, start=2, size=40
		graphView.setViewPort(0, statService.dataSize);
		graphView.setScrollable(true);
		graphView.setManualYAxisBounds(3, 0);
		// optional - activate scaling / zooming
		graphView.setScalable(true);
		// if (timeLabels != null) {
		// String[] labels = {};
		// graphView.setHorizontalLabels(timeLabels.toArray(labels));
		// }

		layout.addView(graphView);
		updateDrinkHistory();
	}

	private void updateDrinkHistory() {
		drinkHistory = new ArrayList<String>();
		drinkEntryList = new ArrayList<String>();
		drinkEntries = new HashMap<String, DrinkEntry>();
		ArrayList<DrinkEntry> drinkHistoryEntries = new ArrayList<DrinkEntry>();
		drinkHistoryHelper = new DrinkHistoryHelper(this);
		if (drinkHistoryHelper != null) {
			try {
				Date date = new Date((long) (new Date().getTime() - DrinkStatService.MILLIS_TO_HOURS_DIVIDER * 24l));
				drinkHistoryEntries = drinkHistoryHelper.getDrinkEntryAfter(date);
			} catch (Exception ex) {
				Log.e(TAG, "Failed to read drink points", ex);
			}
			for (DrinkEntry drinkEntry : drinkHistoryEntries) {
				String key = drinkEntry.getName() + ": " + drinkEntry.getPrice() + getResources().getText(R.string.priceCurrency) + " @ " + drinkEntry.getTimeDrinked().getHours() + ":"
						+ drinkEntry.getTimeDrinked().getMinutes() + ":" + drinkEntry.getTimeDrinked().getSeconds();
				drinkEntryList.add(key);
				drinkEntries.put(key, drinkEntry);
			}
		}
		drinkHistoryList = (ListView) findViewById(R.id.drinkHistory);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.drink_list_item, drinkEntryList);
		drinkHistoryList.setAdapter(adapter);
	}

	@Override
	protected void onResume() {
		super.onResume();
		
		Log.d(TAG, "Resumed to drink manager screen");
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		BackgroundAdapter.updateBackgroundFromPrefs(prefs, this);
		initCustomDrinks();
		updateCounts();
		updateStatistics();
		updateDrinkGraph();
		this.drinks = new ArrayList<Drink>();
//		if (SettingsActivity.localeChanged) {
//	        setContentView(R.layout.drinkmanagerlist);
//	    }
	}

	@Override
	protected void onPause() {
		super.onPause();
		Log.d(TAG, "Paused drink manager screen");
	}

	@Override
	protected void onDestroy() {
		Log.d(TAG, "Destroyed drink manager screen");
		this.drinks = new ArrayList<Drink>();
		super.onDestroy();
	}
}